/**
  作用：    时间控件的统一管理
  创建者：
  时间：
**/
var $J = jQuery ? jQuery : $;
var languageStr = 'zh-cn';
$J(document).ready(function () {
	$J(".wuiDateSpan").each(function(){
		var x = "";
		var select = "";
		var selectId=$J(this).attr("selectId")||"spansel_"+Math.round((Math.random()*100000000));
		var selectValue=$J(this).attr("selectValue");
		var defaultValue=$J(this).attr("_defaultValue")||"";
		var needAllOption = $J(this).attr("_needAllOption");
        var dateFmt = $J(this).attr("datefmt")|| 'yyyy-MM-dd';
        var showDateFmt = $J(this).attr("showdatefmt") || 'yy/MM/dd';
        
		if(selectId){
			select = "<span><select id='"+selectId+"' _defaultValue='"+defaultValue+"' name='"+selectId+"' onchange=\"changeDateForSelect(this,'"+selectId+"_span',null,'"+dateFmt+"','"+showDateFmt+"')\">";
			if(needAllOption!==false&&needAllOption!=="false"){
				select+="<option value='0'>全部</option>";
			}
			select+="<option value='1' "+(selectValue==1?"selected":"")+">今天</option>";
			select+="<option value='2'"+(selectValue==2?"selected":"")+">本周</option>";
			select+="<option value='3'"+(selectValue==3?"selected":"")+">本月</option>";
			select+="<option value='7'"+(selectValue==7?"selected":"")+">上月</option>";
			select+="<option value='4'"+(selectValue==4?"selected":"")+">本季</option>";
			select+="<option value='5'"+(selectValue==5?"selected":"")+">本年</option>";
			select+="<option value='8'"+(selectValue==8?"selected":"")+">上年</option>";
			select+="<option value='6'"+(selectValue==6?"selected":"")+">日期</option>";
			select+="</select></span>";
			x=select+"<span  class='e8selectspan' id='"+selectId+"_span' style='display:"+(selectValue==6?"":"none")+"'>";
		}
		
		_beautyDate(this,x,selectId);	
		if(selectValue && selectValue!="0" && selectValue!="6"){
			jQuery("#"+selectId).trigger("change");
		}
		if(!selectValue){
			var hiddenarea = jQuery(this).children("input[type='hidden']");
			var startDate = hiddenarea.eq(0).val();
			var endDate = hiddenarea.eq(1).val();
			if(startDate==getTodayDate(dateFmt)&&endDate == getTodayDate(dateFmt)){
				jQuery("#"+selectId).val("1");
			}else if(startDate==getWeekStartDate(dateFmt)&&endDate == getWeekEndDate(dateFmt)){
				jQuery("#"+selectId).val("2");
			}else if(startDate==getMonthStartDate(dateFmt)&&endDate == getMonthEndDate(dateFmt)){
				jQuery("#"+selectId).val("3");
			}else if(startDate==getLastMonthStartDate(dateFmt)&&endDate == getLastMonthEndDate(dateFmt)){
				jQuery("#"+selectId).val("7");
			}else if(startDate==getQuarterStartDate(dateFmt)&&endDate == getQuarterEndDate(dateFmt)){
				jQuery("#"+selectId).val("4");
			}else if(startDate==getYearStartDate(dateFmt)&&endDate == getYearEndDate(dateFmt)){
				jQuery("#"+selectId).val("5");
			}else if(startDate==getLastYearStartDate(dateFmt)&&endDate == getLastYearEndDate(dateFmt)){
				jQuery("#"+selectId).val("8");
			}else if(!startDate&&!endDate){
				jQuery("#"+selectId).val("0");
			}else{
				jQuery("#"+selectId).val("6");
				jQuery("#"+selectId+"_span").show();
			}
		}else if(selectValue=="6"){
			jQuery("#"+selectId+"_span").show();
		}
		beautySelect("#"+selectId);
	});
	_beautyDate(null,"","");	
	
});

function _beautyDate(obj,x,selectId){
	var wuiDate = null;
	if(obj){
		wuiDate = $J(obj).find(".wuiDateSel");
	}else{
		wuiDate = $J(".wuiDate");
	}
	wuiDate.each(function(idx,obj1){
		if($J(this).next("button").length>0)return;
		var z = $J(this), n = z.attr("id"), t = z.attr("type"),v = z.val(), b = z.attr("_button"), s = z.attr("_span"), f = z.attr("_callback"), r = z.attr("_isrequired"),vel=z.attr("vel");
		n = (n == undefined || n == null || n == "") ? new Date().getTime() + "_input" : n;
		b = (b == undefined || b == null || b == "") ? n + "ReleBtn_Autogrt" : b;
		s = (s == undefined || s == null || s == "") ? n + "ReleSpan_Autogrt" : s;

		var index = -1;
		if(n.indexOf("_")!=-1){			
			index =  n.substring(n.indexOf("_")+1,n.length);
		}
		if (t != "hidden") {
			z.css("display", "none");	
			z.attr("name", n + "_back");
		}
		if(index!=-1){
			s = s+"_"+index;
		}
		if (t != "hidden") {
			z.css("display", "none");	
			z.attr("name", n + "_back");
		}
		x+="<button class=\"calendar\" type=\"button\" name=" + b + "\" id=" + b + "\" onclick=\"_gdt('" + n + "', '" + s + "','" + vel + "', '" + f + "','"+r+"');\"></button>";
		x += "<span id=\"" + s + "\" name=\"" + s + "\">" + v + "</span>";
		if (r != undefined && r != null && r == "yes") {
			x += "<span id=\"" + s + "img" + "\" name=\"" + s + "img" + "\">";
			if (v == undefined || v == null || v == "") {
				x += "<img align=\"absMiddle\" src=\"/images/BacoError	_wev8.gif\"/>";
			}
			x += "</span>";
			
			//z.bind("propertychange", function () {
			//	checkinput(n, s + "img");
			//});
		}
		if(selectId && idx==wuiDate.length-1){
			x+="</span>";
		}
		if(!obj){
			z.after(x);
			x="";
		}else if(idx!=wuiDate.length-1){
			x+="-"
		}
	});
	if(obj){
		$J(obj).append(x);
	}
}

function changeDateForSelect(obj,id,val,dateFmt,showDateFmt){
	//日期控件select自定义change事件，页面调用的地方可以直接覆盖使用
	try {
		__changeDateForSelect(obj,id,val,dateFmt);
	} catch (e) {}
	if(val==null)val='6';
	var wuiDateSpan = jQuery(obj).closest("span.wuiDateSpan");
	var e8selectspan = wuiDateSpan.children(".e8selectspan");
	var hiddenarea = wuiDateSpan.children("input[type='hidden']");
	var dateSpan = e8selectspan.children("span");
	if(obj.value==val){
		
		e8selectspan.show();
        hiddenarea.eq(0).val(getTodayStartDate(dateFmt));
        dateSpan.eq(0).html(getTodayStartDate(showDateFmt));
        hiddenarea.eq(1).val(getTodayEndDate(dateFmt));
        dateSpan.eq(1).html(getTodayEndDate(showDateFmt));
	}else{
		e8selectspan.hide();
		if(obj.value=="0"){
			hiddenarea.eq(0).val("");
			dateSpan.eq(0).html("");
			hiddenarea.eq(1).val("");
			dateSpan.eq(1).html("");
		}else if(obj.value=="1"){
				hiddenarea.eq(0).val(getTodayStartDate("yyyy-MM-dd 00:00:00"));
				dateSpan.eq(0).html(getTodayStartDate(dateFmt));
				hiddenarea.eq(1).val(getTodayEndDate("yyyy-MM-dd 23:59:59"));
				dateSpan.eq(1).html(getTodayEndDate(dateFmt));
		}else if(obj.value=="2"){
				hiddenarea.eq(0).val(getWeekStartDate(dateFmt));
				dateSpan.eq(0).html(getWeekStartDate(dateFmt));
				hiddenarea.eq(1).val(getWeekEndDate(dateFmt));
				dateSpan.eq(1).html(getWeekEndDate(dateFmt));
		}else if(obj.value=="3"){
				hiddenarea.eq(0).val(getMonthStartDate(dateFmt));
				dateSpan.eq(0).html(getMonthStartDate(dateFmt));
				hiddenarea.eq(1).val(getMonthEndDate(dateFmt));
				dateSpan.eq(1).html(getMonthEndDate(dateFmt));
		}else if(obj.value=="7"){//上个月
				hiddenarea.eq(0).val(getLastMonthStartDate(dateFmt));
				dateSpan.eq(0).html(getLastMonthStartDate(dateFmt));
				hiddenarea.eq(1).val(getLastMonthEndDate(dateFmt));
				dateSpan.eq(1).html(getLastMonthEndDate(dateFmt));
		}else if(obj.value=="4"){
				hiddenarea.eq(0).val(getQuarterStartDate(dateFmt));
				dateSpan.eq(0).html(getQuarterStartDate(dateFmt));
				hiddenarea.eq(1).val(getQuarterEndDate(dateFmt));
				dateSpan.eq(1).html(getQuarterEndDate(dateFmt));
		}else if(obj.value=="5"){
				hiddenarea.eq(0).val(getYearStartDate(dateFmt));
				dateSpan.eq(0).html(getYearStartDate(dateFmt));
				hiddenarea.eq(1).val(getYearEndDate(dateFmt));
				dateSpan.eq(1).html(getYearEndDate(dateFmt));
		}else if(obj.value=="8"){//上一年
				hiddenarea.eq(0).val(getLastYearStartDate(dateFmt));
				dateSpan.eq(0).html(getLastYearStartDate(dateFmt));
				hiddenarea.eq(1).val(getLastYearEndDate(dateFmt));
				dateSpan.eq(1).html(getLastYearEndDate(dateFmt));
		}
	}
}

function _gdt(_i, _s,_v, _f,_r) {
	try {
		var returnValue = _gettheDate(_i, _s,_v,_f,_r);
	} catch(e){} 
}

function _gettheDate(inputname,spanname,_vel, _f,_r){
	var evt = window.event;

	var _minDate = "";
	var _maxDate = "";
	var _dateFmt =""
    var _showDateFmt =""
	try{
        
		_minDate = jQuery("#"+inputname).attr("_minDate");
		_maxDate = jQuery("#"+inputname).attr("_maxDate");
        _dateFmt = jQuery("#"+inputname).attr("datefmt") || 'yyyy-MM-dd';
        _showDateFmt = jQuery("#"+inputname).attr("showdatefmt") || 'yyyy-MM-dd';
		if(_minDate==null){
			_minDate = "";
		}
		if(_maxDate==null){
			_maxDate = "";
		}
	}catch(ex1){}

    WdatePicker({lang:languageStr,
			el : spanname,
            dateFmt:_showDateFmt,
            vel:_vel,
            realDateFmt:_dateFmt,
			onpicked : function(dp) {
				var returnvalue = dp.cal.getDateStr();
				$dp.$(inputname).value = returnvalue;
				if(_r == "yes"){
					//手动触发oninput事件
					checkinput(inputname, spanname + "img");
				}
				if (!window.ActiveXObject) {
					//手动触发oninput事件
					//checkinput(inputname, spanname + "img");
				}
				try {
					if (_f != undefined && _f != null && _f != "") {
						eval(_f + "($dp.$(inputname).value, evt)");	
					}
					
				} catch (e) {}
			},
			oncleared : function(dp) {
				$dp.$(inputname).value = '';
				if(_r == "yes"){
					//手动触发oninput事件
					checkinput(inputname, spanname + "img");
				}
				if (!window.ActiveXObject) {
					//手动触发oninput事件
					//checkinput(inputname, spanname + "img");
				}
			},
			minDate : _minDate,
			maxDate : _maxDate
	});
}

//function $() {
function $ele4p() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string') {
			element = document.getElementById(element);
			
			if (element == undefined || element == null) {
				element = document.getElementsByName(arguments[i])[0];
			}
		}
		if (arguments.length == 1) {
			return element;
		}
		elements.push(element);
	}
	return elements;
}


Date.prototype.format =function(format){
    var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(),    //day
"h+" : this.getHours(),   //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3),  //quarter
"S" : this.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
    (this.getFullYear()+"").substr(4- RegExp.$1.length));
    for(var k in o)if(new RegExp("("+ k +")").test(format))
    format = format.replace(RegExp.$1,
    RegExp.$1.length==1? o[k] :
    ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
}

function addBeginDate(dd,dadd,bt){

	var arr= dd.split("-");
	var btt = bt.split(":");
	var a = new Date(arr[0],arr[1]-1,arr[2],btt[0],btt[1]).valueOf();
	a = (a + dadd * 24 * 60 * 60 * 1000)+60*1000;
	a = new Date(a);
	return a.format("yyyy-MM-dd hh:mm");
}

function addEndDate(dd,dadd,bt){

	var arr= dd.split("-");
	var btt = bt.split(":");
	var a = new Date(arr[0],arr[1]-1,arr[2],btt[0],btt[1]).valueOf();
	a = (a + dadd * 24 * 60 * 60 * 1000)-60*1000;
	a = new Date(a);
	return a.format("yyyy-MM-dd hh:mm");
}
/**
 * 自动转化开始日期,结束日期,工期
 */
/**
function genDateAndWorkday(obj,begindate_,enddate_,workday_,begintime_,endtime_,manager,passnoworktime){
	if(obj&&begindate_&&enddate_&&workday_&&begintime_&&endtime_){
		var bObj= jQuery("#"+begindate_);
		var eObj= jQuery("#"+enddate_);
		var wObj= jQuery("#"+workday_);
		var btObj= jQuery("#"+begintime_);
		var etObj= jQuery("#"+endtime_);
		//alert("manager:"+manager);
		//alert("passnoworktime:"+passnoworktime);
		var curEleName=jQuery(obj).attr("bind");
		if(curEleName==begindate_||curEleName==begintime_){
			WdatePicker({lang:languageStr
				,maxDate:eObj.val()||"2030-12-31"
				,el:begindate_+"span"
				,onpicked:function(dp){
							var returnvalue = dp.cal.getDateStr();
							bObj.val(returnvalue);
							var diff= datediff(bObj.val(),eObj.val());
							if(diff>0){
								wObj.val(diff);
							}else{
								wObj.val("");
							}
						}
				,oncleared:function(dp){
							bObj.val("");
							wObj.val("");
						}
				});
		}else if(curEleName==enddate_||curEleName==endtime_){
			WdatePicker({lang:languageStr
				,minDate:bObj.val()
				,el:enddate_+"span"
				,onpicked:function(dp){
							var returnvalue = dp.cal.getDateStr();
							eObj.val(returnvalue);
							var diff= datediff(bObj.val(),eObj.val());
							if(diff>0){
								wObj.val(diff);
							}else{
								wObj.val("");
							}
						}
				,oncleared:function(dp){
							eObj.val("");
							wObj.val("");
						}
				});
		}else if(curEleName==workday_){
			var b=bObj.val();
			var e=eObj.val();
			var w=wObj.val();
			if(w==""&&b!=""&&e!=""){
				eObj.val("");
				jQuery("#"+enddate_+"span").html("");
			}else if(w!=""&&((b!=""&&e!="")||(b!=""&&e==""))){
				if(w>0){
					var tmpe=addDate(b,(w-1));
					eObj.val(tmpe);
					jQuery("#"+enddate_+"span").html(tmpe);
				}else{
					wObj.val("");
					eObj.val("");
					jQuery("#"+enddate_+"span").html("");
				}
				
			}else if(w!=""&&b==""&&e!=""){
				if(w>0){
					var tmpb=addDate(e,-(w-1));
					bObj.val(tmpb);
					jQuery("#"+begindate_+"span").html(tmpb);
				}else{
					wObj.val("");
					bObj.val("");
					jQuery("#"+begindate_+"span").html("");
				}
				
			}
		}
		
	}
}
**/
function onFlownoShowDate_fnaDateEvent(inputname){
	try{
		var inputValue = jQuery("#"+inputname).val();
		jQuery("#"+inputname).val(inputValue);
		jQuery("#"+inputname+"span").html(inputValue);
		var _obj = $ele4p(inputname);
		var _iptIdOrName = "";
		try{_iptIdOrName = _obj.id;}catch(ex1){}
		if(_iptIdOrName==null||_iptIdOrName==""){
			try{_iptIdOrName = _obj.name;}catch(ex1){}
		}
		var _iptFieldid = _iptIdOrName;
		var _rowIndex = "";
        var inputnameArray = _iptIdOrName.split("_");
        if(inputnameArray.length >= 2){
        	_rowIndex = inputnameArray[inputnameArray.length-1];
		if(_iptIdOrName.indexOf("field")>-1){
        		_iptFieldid = "";
        		for(var i=0;i<inputnameArray.length-1;i++){
        			if(i>0){
        				_iptFieldid += "_";
        			}
        			if(i==0){
        				_iptFieldid += inputnameArray[i].substring("field".length);
        			}else{
        				_iptFieldid += inputnameArray[i];
        			}
			}
        	}
        }else{
        	_iptFieldid = _iptIdOrName.substring("field".length);
        }
        wfbrowvaluechange(_obj, _iptFieldid, _rowIndex);
	}catch(ex012){}
}

/**
*以下是对日期的一些计算函数
*/
var now = new Date(); // 当前日期
var nowDayOfWeek = now.getDay(); // 今天本周的第几天
var nowDay = now.getDate(); // 当前日
var nowMonth = now.getMonth(); // 当前月
var nowYear = now.getYear(); // 当前年
nowYear += (nowYear < 2000) ? 1900 : 0; //

var lastMonthDate = new Date(); // 上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
var lastYear = lastMonthDate.getYear();
var lastMonth = lastMonthDate.getMonth();

// 格局化日期：yyyy-MM-dd
function formatDate(date,dateFmt) {
    return date.pattern(dateFmt)
}

// 获得某月的天数
function getMonthDays(myMonth) {
	var monthStartDate = new Date(nowYear, myMonth, 1);
	var monthEndDate = new Date(nowYear, myMonth + 1, 1);
	var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
	return days;
}

// 获得本季度的开端月份
function getQuarterStartMonth() {
	var quarterStartMonth = 0;
	if (nowMonth < 3) {
		quarterStartMonth = 0;
	}
	if (2 < nowMonth && nowMonth < 6) {
		quarterStartMonth = 3;
	}
	if (5 < nowMonth && nowMonth < 9) {
		quarterStartMonth = 6;
	}
	if (nowMonth > 8) {
		quarterStartMonth = 9;
	}
	return quarterStartMonth;
}

//获取今天的开端日期
function getTodayStartDate(dateFmt){
    return formatDate(now,dateFmt);
}
//获取今天的停止日期
function getTodayEndDate(dateFmt){
    return formatDate(now,dateFmt);
}
// 获得本周的开端日期
function getWeekStartDate(dateFmt) {
	var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
	return formatDate(weekStartDate,dateFmt);
}

// 获得本周的停止日期
function getWeekEndDate(dateFmt) {
	var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
	return formatDate(weekEndDate,dateFmt);
}

// 获得本月的开端日期
function getMonthStartDate(dateFmt) {
	var monthStartDate = new Date(nowYear, nowMonth, 1);
	return formatDate(monthStartDate,dateFmt);
}

// 获得本月的停止日期
function getMonthEndDate(dateFmt) {
	var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
	return formatDate(monthEndDate,dateFmt);
}

// 获得上月开端时候
function getLastMonthStartDate(dateFmt) {
	var lastMonthStartDate = new Date(lastMonth==11?nowYear-1:nowYear, lastMonth, 1);
	return formatDate(lastMonthStartDate,dateFmt);
}

// 获得上月停止时候
function getLastMonthEndDate(dateFmt) {
	var lastMonthEndDate = new Date(lastMonth==11?nowYear-1:nowYear, lastMonth, getMonthDays(lastMonth));
	return formatDate(lastMonthEndDate,dateFmt);
}

// 获得本季度的开端日期
function getQuarterStartDate(dateFmt) {

	var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);
	return formatDate(quarterStartDate,dateFmt);
}

// 或的本季度的停止日期
function getQuarterEndDate(dateFmt) {
	var quarterEndMonth = getQuarterStartMonth() + 2;
	var quarterStartDate = new Date(nowYear, quarterEndMonth,
			getMonthDays(quarterEndMonth));
	return formatDate(quarterStartDate,dateFmt);
}

//获取本年的开端日期
function getYearStartDate(dateFmt){
	var yearStartDate = new Date(nowYear,0,1);
	return formatDate(yearStartDate,dateFmt);
}

//获取本年的结束日期
function getYearEndDate(dateFmt){
	var yearEndDate = new Date(nowYear,11,31);
	return formatDate(yearEndDate,dateFmt);
}

//获取本年的开端日期
function getLastYearStartDate(dateFmt){
	var yearStartDate = new Date(nowYear-1,0,1);
	return formatDate(yearStartDate,dateFmt);
}

//获取本年的结束日期
function getLastYearEndDate(dateFmt){
	var yearEndDate = new Date(nowYear-1,11,31);
	return formatDate(yearEndDate,dateFmt);
}

//获取今天的日期
function getTodayDate(dateFmt){
	return formatDate(now,dateFmt);
}

function beautySelect(selector,_document){
    if(!selector)selector="select[class!=_pageSize]";
    if(!_document)_document=document;
    try{
        jQuery(selector,_document).selectbox({
            effect: "slide",
            onOpen: function(inst){
                var optionsItems=jQuery(this).next().find(".sbOptions");
                var selectValue=jQuery(this).val();

                optionsItems.find("a").removeClass("selectorfontstyle");

                var item=optionsItems.find("a[href='#"+selectValue+"']");

                item.addClass("selectorfontstyle");

            }
        });
        jQuery(window).resize(function(){
            jQuery("select").selectbox("close");
        });
        jQuery(window).scroll(function(e){
            jQuery("select").selectbox("close");
        });
        jQuery(".zDialog_div_content").scroll(function(e){
            jQuery("select").selectbox("close");
            var evt = e||window.event;
            evt.stopPropagation();
            evt.preventDefault();
        });
    }catch(e){if(window.console)console.log(e+"-->jquery.selectbox-0.2.js-->beautySelect");}
}

Date.prototype.pattern = function(fmt)
{ //author: meizz
    var o = {
        "M+" : this.getMonth()+1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
        "H+" : this.getHours(), //小时
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S" : this.getMilliseconds() //毫秒
    };
    var week = {
        "0" : "/u65e5",
        "1" : "/u4e00",
        "2" : "/u4e8c",
        "3" : "/u4e09",
        "4" : "/u56db",
        "5" : "/u4e94",
        "6" : "/u516d"
    };
    if(/(y+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    if(/(E+)/.test(fmt)){
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);
    }
    for(var k in o){
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}